<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/18
 * 描述:
 */

namespace app\result\order;


use app\model\auto\Invoice;
use app\model\auto\OrderInvoice;
use app\model\auto\RechargeLog;
use app\model\Cart;
use app\model\coupon\CouponUser;
use app\model\goods\Goods;
use app\model\goods\GoodsSpecPrice;
use app\model\order\Order;
use app\model\order\OrderCommission;
use app\model\order\OrderExpress;
use app\model\order\OrderGoods;
use app\model\order\OrderLog;
use app\model\user\User;
use app\model\user\UserAddress;
use app\result\auto\AdminMsgResult;
use app\result\BaseResult;
use app\result\CartResult;
use app\result\PaymentResult;
use app\service\AliyunService;
use app\service\CreditService;
use app\service\LockService;
use app\service\OrderService;
use app\service\PaymentService;
use think\facade\Db;

class OrderResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Order();
        //被动触发订单超时检查
        $ckey = 'order_list_pay_expire_check';
        if (!cache($ckey)) {
            cache($ckey, 1, 60);
            OrderService::pay_expire();
        }

    }

    public function list($user_id, $args = [])
    {
        $page = $args['page'] ?? 1;
        $limit = $args['limit'] ?? 10;
        $keywords = $args['keywords'] ?? '';
        $dataType = $args['dataType'] ?? '';
        $where = [];
        $where[] = ['a.user_id', '=', $user_id];
        if ($keywords) {
            $where[] = ['a.order_sn|b.goods_name', 'like', '%' . $keywords . '%'];
        }
        if (!empty($args['created_time'])) {
            $where[] = ['a.created_at', 'between', [$args['created_time'][0], $args['created_time'][1]]];
        }
        if (!empty($args['pay_time'])) {
            $where[] = ['a.pay_time', 'between', [$args['pay_time'][0], $args['pay_time'][1]]];
        }

        if ($dataType == 'payment') {
            $where[] = ['a.order_status', '=', 0];
        } elseif ($dataType == 'received') {
            $where[] = ['a.order_status', '=', 2];
        } elseif ($dataType == 'checking') {
            $where[] = ['a.order_status', '=', 7];
        } elseif ($dataType == 'delivery') {
            $where[] = ['a.order_status', '=', 1];
        } elseif ($dataType == 'comment') {
            $where[] = ['a.order_status', '=', 3];
        }
        $field = 'a.order_id,a.order_sn,a.order_goods_type,a.order_status,a.pay_status,a.total_price,a.shipping_fee,a.coupon_price,a.pay_price,a.created_at';
        $field .= ',a.order_pay_price,a.pay_expire';
        $data = $this->model->alias('a')
            ->join('order_goods b', 'a.order_id=b.order_id', 'left')
            ->where($where)
            ->group('a.order_id')
            ->field($field)
            ->order('a.order_id desc')
            ->page(intval($page), intval($limit))
            ->select()
            ->toArray();

        if ($data) {
            $modelOrderGoods = new OrderGoods();
            foreach ($data as &$v) {
                $v['title'] = $this->get_title_desc($v);
                $v['goods'] = $modelOrderGoods->data_list_nopage(['order_id' => $v['order_id']], 'goods_id,goods_image');
                $v['buttons'] = $this->get_buttons($v);
                $v['order_status_desc'] = self::get_order_status_desc($v['order_status'], $v);
                $v['pay_expire_seconds'] = 0;
                if ($v['order_status'] == 0) {
                    $v['pay_expire_seconds'] = $v['pay_expire'] - time();
                }
            }
            unset($v);
        }
        return self::success_return('success', [
            'list' => $data,
        ]);
    }

    public function get_title_desc($order)
    {
        if ($order['order_goods_type'] == 2) {
            $data['text'] = '虚拟商品';
            $data['color'] = 'red';
        } else {
            $data['text'] = '实物商品';
            $data['color'] = 'blue';
        }
        return $data;
    }

    public static function get_order_status_desc($order_status, $order)
    {
        $desc = [
            0 => '待支付',
            1 => '待发货',
            2 => '待收货',
            3 => '待评价',
            4 => '已完成',
            5 => '售后中',
            6 => '已取消',
            7 => '待审核',
        ];
        return $desc[$order_status] ?? '未知';
    }

    public function get_buttons($order)
    {
        //订单状态：0=待支付，1=待发货，2=待收货，3=待评价，4=已完成，5=售后中，6=已取消，7=待审核
        $buttons = [
            'cancel' => 0,//取消
            'payment' => 0,//支付
            'received' => 0,//收货
            'remind_check' => 0,//催审核
            'remind_send' => 0,//催发货
            'comment' => 0,//评价
            'delete' => 0,//删除
            'after_sale' => 0,//售后
        ];
        if ($order['order_status'] == 0 || $order['order_status'] == 7) {
            $buttons['cancel'] = 1;
        }
        if ($order['pay_status'] == 0 && $order['order_status'] == 0) {
            $buttons['payment'] = 1;
        }
        if ($order['order_status'] == 2) {
            $buttons['received'] = 1;
        }
        if ($order['order_status'] == 3) {
            $buttons['comment'] = 1;
        }
        if ($order['order_status'] == 7) {
            $buttons['remind_check'] = 1;
        }
        if ($order['order_status'] == 1) {
            $buttons['remind_send'] = 1;
        }
        if ($order['order_status'] == 3 || $order['order_status'] == 4 || $order['order_status'] == 6) {
            $buttons['delete'] = 1;
        }
        if (in_array($order['order_status'], [1, 2, 3, 4]) /*&& $order['order_goods_type'] == 1*/) {
            $buttons['after_sale'] = 1;
        }
        return $buttons;
    }

    public function get($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = $this->model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id, 'del_time' => 0])?->toArray();
        if (!$order) {
            return self::error_return('订单不存在');
        }
        $order['order_status_desc'] = self::get_order_status_desc($order['order_status'], $order);
        $order['address'] = json_decode($order['address'], true);
        if ($order['order_goods_type'] === 1 && $order['send_time']) {
            //物流
            $order['express'] = (new OrderExpress())->data_get(['order_id' => $order['order_id']], 'company_code,express_no,express_name');
        }
        $order['pay_expire_seconds'] = 0;
        if ($order['order_status'] === 0) {
            $order['pay_expire_seconds'] = ($order['pay_expire'] - time());//剩余时间，用于倒计时
        }

        $order['amount_list'] = [
            ['name' => '商品总价：', 'value' => $order['total_price'], 'symbol' => '￥'],
            ['name' => '优惠金额：', 'value' => $order['coupon_price'], 'symbol' => '￥'],
            ['name' => '应付金额：', 'value' => $order['order_pay_price'], 'symbol' => '￥'],
            ['name' => '运费：', 'value' => $order['shipping_fee'], 'symbol' => '￥'],
            ['name' => '积分抵扣：', 'value' => $order['integral_price'] ?? '0.00', 'symbol' => '￥'],
            ['name' => '实付金额：', 'value' => $order['pay_price'] > 0 ? $order['pay_price'] : '0.00', 'symbol' => '￥'],
        ];
        if ($order['admin_reduce_price'] > 0) {
            $order['amount_list'][] = ['name' => '后台优惠：', 'value' => $order['admin_reduce_price'], 'symbol' => '￥'];
        }
        $order['buttons'] = $this->get_buttons($order);
        $order['goods'] = (new OrderGoods())->data_list_nopage(['order_id' => $order['order_id']]);
        $order['invoice'] = self::query_order_invoice($order['order_id']);

        return self::success_return('success', [
            'order_info' => $order,
            'payment_list' => (new PaymentResult())->payment_list($user_id, $args)
        ]);
    }

    public static function query_order_invoice($order_id)
    {
        $invoice = (new OrderInvoice())->data_get(['order_id' => $order_id]);
        if ($invoice) {
            return [
                ['name' => '发票抬头：', 'value' => $invoice['title']],
                ['name' => '税号：', 'value' => $invoice['tax_number'],],
                ['name' => '公司电话：', 'value' => $invoice['mobile'] ?? '--',],
                ['name' => '邮箱：', 'value' => $invoice['email'] ?? '--',],
                ['name' => '开户银行：', 'value' => $invoice['bank_name'] ?? '--',],
                ['name' => '开户账号：', 'value' => $invoice['bank_account'] ?? '--',],
                ['name' => '单位地址：', 'value' => $invoice['address'] ?? '--',],
                ['name' => '发票类型：', 'value' => $invoice['type'] == 0 ? '普通增值税' : '专业增值税',],
            ];
        }
        return null;
    }

    public function remain_check($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        $type = $args['type'] ?? 'check';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = $this->model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id, 'del_time' => 0], 'order_id,order_sn');
        if (!$order) {
            return self::error_return('订单不存在');
        }
        $ckey = 'order_remind_check_' . $order_sn . $type;
        if (cache($ckey)) {
            return self::error_return('已经提交催审，请耐心等待商家处理');
        }
        cache($ckey, 1, 3600 * 5);
        self::add_order_log([
            'order_sn' => $order_sn,
            'order_id' => $order['order_id'],
            'remark' => '用户催审',
        ]);
        AdminMsgResult::push_msg([
            'title' => '订单' . ($type == 'send' ? '催发货' : '催审核'),
            'content' => '用户催单啦！！！,订单编号：' . $order_sn,
            'link' => '/order/detail?order_id=' . $order['order_id'],
        ]);
        return self::success_return('催审成功，请耐心等待商家处理');
    }

    public function delete($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = $this->model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id, 'del_time' => 0], 'order_id,order_sn,parent_user_id');
        if (!$order) {
            return self::error_return('订单不存在');
        }
        $res = $this->model->data_update(['order_sn' => $order_sn, 'user_id' => $user_id], ['del_time' => time()]);
        if (!$res) {
            return self::error_return('删除失败');
        }
        if (!empty($order['parent_user_id'])) {
            (new OrderCommission())->data_update(['order_id' => $order['order_id']], ['status' => -1]);//佣金取消
        }
        self::add_order_log([
            'order_id' => $order['order_id'],
            'order_sn' => $order_sn,
            'remark' => '用户删除订单',
        ]);
        return self::success_return('订单已删除');
    }

    public function cancel($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = $this->model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id, 'del_time' => 0], 'order_id,order_sn,cancel_time,parent_user_id');
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if ($order['cancel_time']) {
            return self::error_return('订单已取消');
        }
        $res = $this->model->data_update(['order_id' => $order['order_id']], ['order_status' => 6, 'cancel_time' => date('Y-m-d H:i:s')]);
        if (!$res) {
            return self::error_return('取消失败');
        }
        if (!empty($order['parent_user_id'])) {
            (new OrderCommission())->data_update(['order_id' => $order['order_id']], ['status' => -1]);//佣金取消
        }
        self::add_order_log([
            'order_id' => $order['order_id'],
            'order_sn' => $order['order_sn'],
            'remark' => '用户取消订单',
        ]);
        return self::success_return('取消成功');
    }

    // 确认收货
    public function confirm($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = $this->model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id, 'del_time' => 0], 'order_id,order_sn,order_status');
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if ($order['order_status'] != 2) {
            return self::error_return('订单状态不支持确认收货');
        }
        $res = $this->model->data_update(['order_id' => $order['order_id']], ['order_status' => 3, 'received_time' => date('Y-m-d H:i:s')]);
        if (!$res) {
            return self::error_return('确认收货失败');
        }
        self::add_order_log([
            'order_id' => $order['order_id'],
            'order_sn' => $order['order_sn'],
            'remark' => '用户确认收货',
        ]);
        return self::success_return('确认收货成功');
    }

    public function data_count($user_id, $args = [])
    {
        $where = [];
        $where['user_id'] = $user_id;

        $data = [
            ['label' => '待付款', 'value' => $this->model->data_count(array_merge($where, ['order_status' => 0])), 'type' => 'payment'],
            ['label' => '待审核', 'value' => $this->model->data_count(array_merge($where, ['order_status' => 7])), 'type' => 'checking', 'icon' => 'clock'],
            ['label' => '待发货', 'value' => $this->model->data_count(array_merge($where, ['order_status' => 1])), 'type' => 'delivery', 'icon' => 'hourglass'],
            ['label' => '待收货', 'value' => $this->model->data_count(array_merge($where, ['order_status' => 2])), 'type' => 'received', 'icon' => 'car'],
            ['label' => '待评价', 'value' => $this->model->data_count(array_merge($where, ['order_status' => 3])), 'type' => 'comment', 'icon' => 'chat'],
        ];
        return self::success_return('success', $data);
    }

    private static function get_order_sn()
    {
        return 'BS' . date('YmdHis') . rand(1000, 9999);
    }

    public function create($user_id, $args = [])
    {
        $remark = $args['remark'] ?? '';
        $address_id = $args['address_id'] ?? '0';
        $coupon_id = intval($args['coupon_id'] ?? 0);
        $invoice_id = intval($args['invoice_id'] ?? 0);

        $order_type = $args['order_type'] ?? '';
        if (!$order_type) {
            return self::error_return('参数错误');
        }
        $pay_way = $args['pay_way'] ?? '1';
        $getGoodsList = (new CartResult())->get_goods_list($user_id, $args, $order_type == 'buyNow' ? 'buyNow' : 'cart');
        if ($getGoodsList['code'] !== 0) {
            return $getGoodsList;
        }
        $goodsList = $getGoodsList['data'];
        $order_goods_type = $goodsList[0]['goods_type'];//1普通商品，2虚拟商品
        $needAddress = true;
        if ($order_goods_type == 2) {
            $needAddress = false;
        }
        if ($needAddress) {
            if (!$address_id) {
                return self::error_return('请选择收货地址');
            }
            $address = (new UserAddress())->data_get(['address_id' => $address_id, 'user_id' => $user_id]);
            if (!$address) {
                return self::error_return('请选择收货地址');
            }
        }
        if ($coupon_id) {
            $coupon = (new CouponUser())->data_get(['id' => $coupon_id, 'user_id' => $user_id, 'status' => 0]);
            if (!$coupon) {
                return self::error_return('优惠券无效');
            }
        }
        if ($invoice_id) {
            $invoiceInfo = (new Invoice())->data_get(['invoice_id' => $invoice_id, 'user_id' => $user_id]);
            if (!$invoiceInfo) {
                return self::error_return('发票信息无效');
            }
        }
        $lock = $user_id . '_' . $order_type;
        if (!LockService::logck_by_second($lock, 6, true)) {
            return self::error_return('正在处理，请勿重复提交');
        }

        $total_price = array_sum(array_column($goodsList, 'total_price'));
        $coupon_price = 0;
        if (!empty($coupon)) {
            if ($coupon['min_price'] > $total_price) {
                LockService::unlock($lock);
                return self::error_return('优惠券不满足使用条件');
            }
            if ($coupon['coupon_type'] == 10) {
                $coupon_price = $coupon['reduce_price'];
            } else {
                $coupon_price = bcmul((10 - $coupon['discount']) / 10, $total_price, 2);
            }
        }
        $userInfo = (new User())->data_get(['user_id' => $user_id], 'parent_id,source_parent_id');

        $orderPayPrice = $total_price - $coupon_price;//应付
        $isOpenCommission = config('commission.open');
        //分销订单
        if ($isOpenCommission && !empty($userInfo['parent_id'])) {
            $commissionOrder = [];
            $commissionConf = config('commission');
            $parentRate = $commissionConf['rate']['parent'];
            $sourceParentRate = $commissionConf['rate']['source_parent'];
            if ($parentRate > 0 && bcmul($parentRate, $orderPayPrice, 2) > 0) {

                $commissionOrder[] = [
                    'user_id' => $userInfo['parent_id'],
                    'commission_rate' => $parentRate,
                    'commission_price' => bcmul($parentRate, $orderPayPrice, 2),
                    'source_pay_price' => $orderPayPrice,
                    'order_id' => 0,
                    'order_sn' => '',
                ];
            }
            if ($sourceParentRate > 0 && $userInfo['source_parent_id'] && bcmul($sourceParentRate, $orderPayPrice, 2) > 0) {
                $commissionOrder[] = [
                    'user_id' => $userInfo['source_parent_id'],
                    'commission_rate' => $sourceParentRate,
                    'commission_price' => bcmul($sourceParentRate, $orderPayPrice, 2),
                    'source_pay_price' => $orderPayPrice,
                    'order_id' => 0,
                    'order_sn' => '',
                ];
            }
        }
        if ($pay_way == 4) {
            $userMoney = (new User())->get_value(['user_id' => $user_id], 'credit');
            if ($userMoney < $orderPayPrice) {
                LockService::unlock($lock);
                return self::error_return('余额不足');
            }
        }
        $baseData = [
            'user_id' => $user_id,
            'pay_type' => $pay_way,
            'pay_status' => 0,
            'order_status' => $pay_way == 3 ? 7 : 0,
            'total_price' => $total_price,
            'shipping_fee' => 0,
            'pay_price' => 0,
            'order_pay_price' => $orderPayPrice,
            'remark' => $remark,
            'address' => $needAddress ? json_encode($address, JSON_UNESCAPED_UNICODE) : '',
            'coupon_price' => $coupon_price,
            'user_coupon_id' => $coupon_id,
            'order_goods_type' => $order_goods_type,
            'pay_expire' => time() + 3600,//1小时
            'parent_user_id' => $userInfo['parent_id'] ?? 0,
            'source_parent_user_id' => $userInfo['source_parent_id'] ?? 0,
        ];


        try {
            Db::startTrans();
            $order_sn = self::get_order_sn();
            $baseData['order_sn'] = $order_sn;
            $order_id = (new Order())->data_add($baseData);
            if (!$order_id) {
                throw new \Exception('创建订单忙碌，请重试');
            }
            foreach ($goodsList as $goods) {
                // 计算每个商品占订单总价的比例
                $proportion = $goods['total_price'] / $total_price;
                // 计算每个商品的优惠金额
                $goods_coupon_price = $coupon_price * $proportion;
                $order_goods = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'order_id' => $order_id,
                    'goods_id' => $goods['goods_id'],
                    'goods_price' => $goods['goods_price'],
                    'goods_count' => $goods['total_num'],
                    'goods_total_old_price' => $goods['total_price'],
                    'goods_total_price' => $goods['total_price'] - $goods_coupon_price,
                    'coupon_price' => $goods_coupon_price,
                    'goods_spec' => $goods['spec_name'] ?? '',
                    'goods_spec_id' => $goods['spec_id'] ?? 0,
                    'goods_name' => $goods['goods_name'],
                    'goods_image' => $goods['goods_image'],
                ];
                $order_goods_id = (new OrderGoods())->data_add($order_goods);
                if (!$order_goods_id) {
                    throw new \Exception('创建订单详情忙碌，请重试');
                }
                if (!empty($goods['spec_id'])) {
                    //库存扣减
                    $res = (new GoodsSpecPrice())->data_update(['spec_id' => $goods['spec_id']], ['store_count' => $goods['store_count'] - $goods['total_num']]);
                    if (!$res) {
                        throw new \Exception('库存扣减失败');
                    }
                } else {
                    $res = (new Goods())->data_update(['goods_id' => $goods['goods_id']], ['store_count' => $goods['store_count'] - $goods['total_num']]);
                    if (!$res) {
                        throw new \Exception('库存扣减失败');
                    }
                }
            }
            if ($coupon_id) {
                //更新优惠券状态
                (new CouponUser())->data_update(['id' => $coupon_id], ['status' => 1]);
            }
            if (!empty($invoiceInfo)) {
                $addInvoiceLog = (new OrderInvoice())->data_add([
                    'invoice_id' => $invoiceInfo['invoice_id'],
                    'order_id' => $order_id,
                    'order_sn' => $order_sn,
                    'title' => $invoiceInfo['title'],
                    'tax_number' => $invoiceInfo['tax_number'],
                    'mobile' => $invoiceInfo['mobile'],
                    'email' => $invoiceInfo['email'],
                    'type' => $invoiceInfo['type'],
                    'bank_name' => $invoiceInfo['bank_name'],
                    'bank_account' => $invoiceInfo['bank_account'],
                    'address' => $invoiceInfo['address'],
                    'status' => 0,
                ]);
                if (!$addInvoiceLog) {
                    throw new \Exception('创建发票信息失败');
                }
            }
            //分销订单记录
            if (!empty($commissionOrder)) {
                foreach ($commissionOrder as &$item) {
                    $item['order_id'] = $order_id;
                    $item['order_sn'] = $order_sn;
                }
                unset($item);
                $res = (new OrderCommission())->saveAll($commissionOrder);
                if (!$res) {
                    throw new \Exception('创建分享订单失败');
                }
            }
            if ($order_type === 'cart') {
                $cart_ids = $args['cart_ids'] ?? "";
                $cart_ids = array_filter(explode(',', $cart_ids));
                //删除购物车
                (new Cart())->data_del([['user_id', '=', $user_id], ['id', 'in', $cart_ids]]);
            }
            //余额支付
            if ($pay_way == 4) {
                $creditAction = CreditService::credit_action($user_id, -$orderPayPrice, [
                    'order_sn' => $order_sn,
                    'remark' => '订单支付'
                ]);
                if (!$creditAction) {
                    throw new \Exception('余额扣除失败');
                }
                $upOrder = (new Order())->data_update(['order_id' => $order_id], [
                    'pay_status' => 1,
                    'order_status' => 1,
                    'pay_price' => $orderPayPrice,
                    'pay_time' => date('Y-m-d H:i:s'),
                    'pay_type' => $pay_way,
                    'trans_no' => $trans_no ?? "",
                ]);
                if (!$upOrder) {
                    throw new \Exception('更新订单失败');
                }
                if (config('point.open') && config('point.order')) {
                    $point = config('point.order');//1元1积分转换
                    $point = $orderPayPrice * $point;
                    if ($point >= 1) {
                        $pointAction = (new CreditService())->point_action($user_id, $point, [
                            'order_sn' => $order_sn,
                            'remark' => '订单支付赠送'
                        ]);
                    }

                }
            }

        } catch (\Exception $e) {
            Db::rollback();
            LockService::unlock($lock);
            return self::error_return('创建订单失败：' . $e->getMessage());
        }
        Db::commit();
        self::add_order_log([
            'order_id' => $order_id,
            'order_sn' => $order_sn,
            'remark' => '创建订单'
        ]);
        $pay_way = $args['pay_way'] ?? '';
        if ($pay_way == '1' || $pay_way == '2') {
            if ($pay_way == 2) {
                if (BS_FROM == 'app') {
                    $req = (new PaymentService())->alipay([
                        'order_sn' => $order_sn,
                        'order_amount' => $baseData['order_pay_price'],
                        'subject' => '订单支付'
                    ]);
                } else {
                    $domain = request()->domain();
                    $url = $domain . '/api/payment/cashier?order_sn=' . $order_sn . '&title=收银台&api_base_url=' . $domain . '&token=' . ($args['token'] ?? '');
                }

                return self::success_return('订单生已创建，请尽快支付', [
                    'order_sn' => $order_sn,
                    'params' => $req ?? null,
                    'url' => $url ?? ""
                ]);

            }
            return self::success_return('订单生成成功，此支付方式正在接入中...', [
                'order_sn' => $order_sn,
                'pay_status' => -1,
                'param' => []
            ]);
        } elseif ($pay_way == 4) {
            OrderResult::add_order_log([
                'order_id' => $order_id,
                'order_sn' => $order_sn,
                'remark' => '支付成功',
            ]);
            return self::success_return('订单支付完成', [
                'order_sn' => $order_sn,
                'pay_status' => 0,
                'param' => []
            ]);
        }
        return self::success_return('订单已提交审核，请等待管理员审核', [
            'order_sn' => $order_sn,
            'pay_status' => 0,
        ]);
    }

    public function express($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('缺少参数');
        }
        $express = (new OrderExpress())->data_get([['order_sn', '=', $order_sn]], 'express_name,express_no,track_logs,last_query_time');
        if (!$express) {
            return self::error_return('订单未发货');
        }
        $data = [
            'info' => [
                'order_sn' => $order_sn,
                'express_name' => $express['express_name'] ?? '',
                'express_no' => $express['express_no'] ?? '',
            ]
        ];
        //x小时内不查询
        $hours = !empty($express['track_logs']) ? 3 : 1;
        if ($express['last_query_time'] > date('Y-m-d H:i:s', time() - 3600 * $hours)) {
            $data['info']['logs'] = $express['track_logs'] ? json_decode($express['track_logs'], true) : [];
        }
        $res = AliyunService::kd($express['express_no'], '', $order_sn);
        if ($res['code'] != 0) {
            return self::error_return($res['msg']);
        }

        if ($res['data']['list']) {
            $data['info']['logs'] = $res['data']['list'];
            //更新物流信息
            (new OrderExpress())->data_update([
                'order_sn' => $order_sn,
                'express_no' => $express['express_no'],
            ], [
                'company_code' => $res['data']['type'],
                'express_name' => $res['data']['express_name'],
                'track_logs' => json_encode($res['data']['list'], JSON_UNESCAPED_UNICODE),
                'last_query_time' => date('Y-m-d H:i:s'),
            ]);
        }
        return self::success_return('获取成功', $data);
    }

    /**
     * 添加订单日志
     * @param $args array ['order_id'=>'','order_sn'=>'','remark'=>'']
     * @return bool
     */
    public static function add_order_log($args)
    {
        $baseData = [
            'order_id' => $args['order_id'] ?? '',
            'order_sn' => $args['order_sn'] ?? '',
            'remark' => $args['remark'] ?? '',
        ];
        return (bool)(new OrderLog())->data_add($baseData);
    }

    //订单支付状态检测
    public function pay_check($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('缺少参数');
        }
        if (str_starts_with($order_sn, 'REC')) {
            $order = (new RechargeLog())->data_get([['order_sn', '=', $order_sn]], 'pay_status,money as pay_price,pay_type');

        } else {
            $order = (new Order())->data_get([['order_sn', '=', $order_sn], ['user_id', '=', $user_id]], 'pay_status,pay_price,pay_type');
        }

        if (!$order) {
            return self::error_return('订单不存在');
        }

        if ($order['pay_status'] == 1) {
            return self::success_return('订单已支付', [
                'order_sn' => $order_sn,
                'pay_status' => 1,
            ]);
        }
        return self::error_return('订单未支付', [
            'order_sn' => $order_sn,
            'pay_status' => 0,
        ]);
    }

    public static function get_pay_type_desc($pay_type)
    {
        //支付方式：1=微信，2=支付宝，3=转账，4=余额
        $pay_type_desc = [
            1 => '微信',
            2 => '支付宝',
            3 => '转账',
            4 => '余额',
        ];
        return $pay_type_desc[$pay_type] ?? '其它';
    }
}
